/**
 * 微信小程序授权认证逻辑
 *
 */
import { store } from "@/store";
import {
  ApiWxUserLogin,
  ApiWxUserPhoneRegister,
  ApiUserUpdateUserInfo,
  ApiWxUserInfo,
} from "@/api/auth";
import { setAuth, setUserInfo } from "@/store/reducers/user";
import Taro from "@tarojs/taro";
import { getUserInfo } from "@/lib/auth";
import { instance as Log } from "@/lib/log";

/**
 * 获取用户token, 并获取用户信息
 * @returns
 */
export const getAuthToken = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success: (res) => {
        ApiWxUserLogin({
          code: res.code,
          appId: process.env.APPID,
        })
          .then((response) => {
            store.dispatch(
              setAuth({
                token: response.data.userLoginResponse.token,
                exipreTime: response.data.userLoginResponse.exipreTime,
              })
            );
            getUserInfo({
              token: response.data.userLoginResponse.token,
              exipreTime: response.data.userLoginResponse.exipreTime,
            });
            resolve(true);
          })
          .catch((error) => {
            Taro.showToast({
              title: error?.msg || "登录失败",
              icon: "none",
              duration: 2000,
            });
            reject();
          });
      },
      fail: () => {
        reject();
      },
    });
  });
};

/**
 * 授权手机号并登录
 * @returns
 */
export const getPhoneNumber = (e, callback) => {
  return new Promise((resolve, reject) => {
    wx.login({
      success: (r) => {
        ApiWxUserLogin({
          code: r.code,
          appId: process.env.APPID,
        })
          .then((login) => {
            const { token, exipreTime } = login.data;
            getUserInfo({ token, exipreTime, callback });
            resolve(token);
          })
          .catch((error) => {
            if (error?.code === "1320") {
              wx.login({
                success: (r) => {
                  const localUserInfo: any =
                    wx.getStorageSync(WECHART_USERINFO) || {};
                  ApiWxUserPhoneRegister({
                    iv: e.detail.iv,
                    encryptedData: e.detail.encryptedData,
                    openId: error.data.openId,
                    appId: process.env.APPID,
                    code: r.code,
                    headImage: localUserInfo.avatarUrl,
                    nickName: localUserInfo.nickName,
                  })
                    .then((res) => {
                      Taro.showToast({
                        title: "登录成功",
                        icon: "none",
                        duration: 2000,
                      });
                      const { token, exipreTime } = res.data;
                      getUserInfo({
                        token,
                        exipreTime,
                        callback,
                      });
                      resolve(token);
                    })
                    .catch((e) => {
                      Taro.showToast({
                        title: e?.msg || "登录失败",
                        icon: "none",
                        duration: 2000,
                      });
                      reject(e);
                    });
                },
              });
            } else {
              Taro.showToast({
                title: error?.msg || "登录失败",
                icon: "none",
                duration: 2000,
              });
              reject(error);
            }
          });
      },
      fail: () => {
        reject();
      },
    });
  });
};

/**
 * 本地缓存微信用户信息的key
 */
export const WECHART_USERINFO = "wechartUserInfo";
/**
 * 最新版本 授权用户信息
 * @param {}
 * @return
 */
export const getChooseAvatarUserProfile = (
  { avatarUrl, nickName },
  callback = () => {}
) => {
  const { user } = store.getState();
  const { auth } = user || {};
  const { token } = auth || {};
  store.dispatch(
    setUserInfo({
      headImg: avatarUrl,
      nickName: nickName,
    })
  );
  if (token) {
    ApiUserUpdateUserInfo({ headImg: avatarUrl, nickName })
      .then(() => {
        callback();
      })
      .finally(() => {});
  } else {
    callback();
  }
};
/**
 * 用户授权微信个人信息
 * @returns
 */
export const getUserProfile = () => {
  return new Promise((resolve, reject) => {
    wx.getUserProfile({
      desc: "用于完善会员资料", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (data) => {
        wx.login({
          success: (r) => {
            ApiWxUserInfo({
              signature: data.signature,
              rawData: data.rawData,
              encryptedData: data.encryptedData,
              iv: data.iv,
              code: r.code,
              appId: process.env.APPID,
            });
          },
        });
        wx.setStorageSync(WECHART_USERINFO, data.userInfo);
        const { user } = store.getState();
        const { auth } = user || {};
        const { token } = auth || {};
        if (token) {
          ApiUserUpdateUserInfo({
            headImg: data.userInfo.avatarUrl,
            nickName: data.userInfo.nickName,
          })
            .then(() => {
              resolve(data.userInfo);
            })
            .finally(() => {});
        } else {
          resolve(data.userInfo);
        }
      },
      fail: (e) => {
        reject(e);
      },
    });
  });
};

/**
 * 用户授权微信个人信息 - 兼容老版本
 * @returns
 */
export const getUserInfoForOld = (e, getUnitionID?) => {
  const data = e.detail;
  return new Promise((resolve, reject) => {
    const { user } = store.getState();
    const { auth } = user || {};
    const { token } = auth || {};
    if (getUnitionID) {
      wx.login({
        success: (r) => {
          ApiWxUserInfo({
            signature: data.signature,
            rawData: data.rawData,
            encryptedData: data.encryptedData,
            iv: data.iv,
            code: r.code,
            appId: process.env.APPID,
          })
            .then(() => {
              resolve(data.userInfo);
            })
            .catch((e) => {
              reject(e);
            });
        },
      });
      return;
    }
    wx.setStorageSync(WECHART_USERINFO, data.userInfo);
    if (token) {
      ApiUserUpdateUserInfo({
        headImg: data.userInfo.avatarUrl,
        nickName: data.userInfo.nickName,
      })
        .then(() => {
          resolve(data.userInfo);
        })
        .finally(() => {});
    } else {
      resolve(data.userInfo);
    }
  });
};

/**
 * 保存到相册
 */
export const handleSaveToAlbum = (image, { local, arraybuffer }: any = {}) => {
  if (arraybuffer) {
    wx.showLoading({
      title: "加载中",
      duration: 0,
    });
    wx.request({
      url: image, // 二进制文件远程资源链接
      responseType: "arraybuffer",
      success: (res) => {
        // 创建文件管理器
        const mannger = wx.getFileSystemManager();
        // 命名地址 注意 我这里是字节小程序的地址 微信的地址可以把'ttfile://user/'换为 wx.env.USER_DATA_PATH
        // 因为是图片所以我直接写为.jpg    应该需要判断文件类型
        const getTime = new Date().getTime();
        const filePath = `${wx.env.USER_DATA_PATH}/${getTime}.png`;
        // 写入文件
        mannger.writeFile({
          filePath, // 写入临时文件的地址
          data: res.data, // 二进制码
          encoding: "base64", // 写入格式，因为是图片 pdf的话写utf8
          success(_res) {
            // 图片保存
            init(filePath);
          },
        });
      },
    });
    return;
  }
  Log.log("保存到相册", image, local);
  function init(file) {
    // 生产环境时 记得这里要加入获取相册授权的代码
    // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.writePhotosAlbum" 这个 scope
    wx.getSetting({
      success(res) {
        if (!res.authSetting["scope.writePhotosAlbum"]) {
          wx.authorize({
            scope: "scope.writePhotosAlbum",
            success() {
              // 用户已经同意小程序相册功能，后续调用 wx.saveImageToPhotosAlbum 接口不会弹窗询问
              startSaveImage(file);
            },
            fail(e) {
              Taro.showToast({
                title:
                  '您未授权，请点击右上角"..."三个点，进入"设置"，允许"添加到相册"',
                icon: "none",
                duration: 4000,
              });
            },
          });
        } else {
          startSaveImage(file);
        }
      },
      finally() {
        wx.hideLoading();
      },
    });
  }
  wx.showLoading({
    title: "加载中",
    duration: 0,
  });
  if (local) {
    init(image);
    return;
  }
  wx.downloadFile({
    url: image, // 图片地址
    success(imageRes) {
      init(imageRes.tempFilePath);
      wx.hideLoading();
    },
    fail() {
      Taro.showToast({
        title: `图片下载失败，图片路径：${image}`,
        icon: "none",
        duration: 4000,
      });
      wx.hideLoading();
    },
  });
};
const startSaveImage = (tempFilePath) => {
  Log.log("保存到相册startSaveImage", tempFilePath);
  wx.saveImageToPhotosAlbum({
    filePath: tempFilePath,
    success() {
      Taro.showToast({
        title: `保存成功`,
        icon: "success",
        duration: 4000,
      });
    },
    fail() {
      wx.hideLoading();
    },
  });
};

/**
 * 版本比较
 * @param {}
 * @return
 */
export function compareVersion(v1) {
  if (process.env.TARO_ENV !== "weapp") return;

  let v2 = wx.getSystemInfoSync().SDKVersion;
  console.log("比较版本", v1);
  console.log("当前环境版本", v2);
  v1 = v1.split(".");
  v2 = v2.split(".");
  const len = Math.max(v1.length, v2.length);

  while (v1.length < len) {
    v1.push("0");
  }
  while (v2.length < len) {
    v2.push("0");
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i], 10);
    const num2 = parseInt(v2[i], 10);

    if (num1 > num2) {
      return 1;
    } else if (num1 < num2) {
      return -1;
    }
  }

  return 0;
}
